<template>
  <div>
    <h3 class="title">
      <span v-if="formDis ===false && isEdit === false">上传试题</span>
      <span v-if="isEdit">编辑试题</span>
      <!-- <span v-if="formDis === true">查看详情</span> -->
      <!-- {{ $route.query }} -->

    </h3>
    <ul v-if="isEdit" class="score_number">
      <li v-for="(item, index) in questionList" :class="{'active': courseNum === (index+1)}" :key="index" @click="chooseScore(index)">
        <span>{{ item.number }}</span><br>
        <!-- <span>{{ item.title }}</span> -->
      </li>
    </ul>
    <!-- +++{{ $route.query.id }}+++ -->
    <el-form ref="ruleForm" :disabled="formDis" :model="ruleForm" :rules="rules" label-width="130px" class="demo-ruleForm" style="margin-top: 20px;">
      <!-- {{ questionList.length }}<br><br> -->
      <!-- {{ courseNum }}
      {{ questionList }} -->
      <!-- {{ ruleForm }} -->
      <el-form-item :label="`试题${ruleForm.number}题目`" prop="title">
        <el-col :span="10" >
          <el-input v-model="ruleForm.title" type="textarea" maxlength="100" />
        </el-col>
      </el-form-item>
      <!-- <el-form-item :label="`试题${ruleForm.number}分值`" prop="score">
        <el-col :span="10" >
          <el-input v-model="ruleForm.score" type="number" />
        </el-col>
      </el-form-item> -->
      <el-form-item :label="`试题${ruleForm.number}选项`" class="add_tip" prop="discount">
        <el-form-item prop="optionsA">
          <el-col :span="1" style="text-align: center;">A:</el-col>
          <el-col :span="9" >
            <el-input v-model="ruleForm.optionsA"/>
          </el-col>
        </el-form-item>
        <el-form-item prop="optionsB" class="mt10">
          <el-col :span="1" style="text-align: center;">B:</el-col>
          <el-col :span="9" >
            <el-input v-model="ruleForm.optionsB"/>
          </el-col>
        </el-form-item>
        <el-form-item prop="optionsC" class="mt10">
          <el-col :span="1" style="text-align: center;">C:</el-col>
          <el-col :span="9" >
            <el-input v-model="ruleForm.optionsC"/>
          </el-col>
        </el-form-item>
        <el-form-item prop="optionsD" class="mt10">
          <el-col :span="1" style="text-align: center;">D:</el-col>
          <el-col :span="9" >
            <el-input v-model="ruleForm.optionsD"/>
          </el-col>
        </el-form-item>
      </el-form-item>
      <el-form-item :label="`试题${ruleForm.number}答案`" prop="answer">
        <el-col :span="6" >
          <el-select v-model="ruleForm.answer" placeholder="请选试题答案">
            <el-option v-for="(item, index) in chooseList" :value="item" :label="item" :key="index"/>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button v-preventReClick type="primary" @click="nextQuestion('ruleForm')">添加试题</el-button>
        <el-button v-preventReClick type="success" @click="submitForm('ruleForm')">提交</el-button>
        <el-button v-preventReClick v-if="questionList.length>1" type="danger" @click="delCur('ruleForm')">删除当前试题</el-button>
        <el-button v-preventReClick type="" @click="$router.go(-1)">返回</el-button>
        <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import Vue from 'vue'
import config from '@/utils/config';
import Tinymce from '@/components/Tinymce'
import { GetQiniuToken } from '@/utils/qiniuUpload.js'
import { Message } from 'element-ui'
import mixin from '@/mixin'
import { addQuestion, getQuestionInfo, editQuestion, delsingleQuestion } from '@/api/course'

export default {
  components: { Tinymce },
  mixins: [mixin],
  data() {
    return {
      chooseList: ['A', 'B', 'C', 'D'],
      courseNum: 1,
      courseId: '',
      questionList: [
      ],
      ruleForm: {
        courseId: '',
        number: 0,
        title: '',
        score: '',
        optionsA: null,
        optionsB: null,
        optionsC: null,
        optionsD: null,
        answer: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入试题题目', trigger: 'blur' }
        ],
        score: [
          { required: true, message: '请输试题分值', trigger: 'blur' },
          { pattern: /^(?!(0[0-9]{0,}$))[0-9]{1,}[.]{0,}[0-9]{0,}$/, message: '数值需大于0', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请选择试题答案', trigger: 'change' }
        ]
      },
      formDis: false,
      tinymceDis: false,
      isEdit: false,
      selectShow: false,
      isDisabled: false,
      limitQuestion: 100
    }
  },
  computed: {
  },
  watch: {
    ruleForm: {
      handler: function(nowVal, oldVal) {
        this.$store.dispatch('AddlistenForm', this.ruleForm).then(() => {
        }).catch((err) => {
          Message.error(err.err)
        })
      },
      deep: true
    }
  },
  created() {
    this.ruleForm.number = this.courseNum
    this.ruleForm.courseId = this.courseId
    this.questionList.push(this.ruleForm)
  },
  mounted() {
    const _self = this;
    console.log('this.$route.query:', JSON.stringify(this.$route.query))
    if (this.$route.query && JSON.stringify(this.$route.query) !== '{}') {
      this.isEdit = this.$route.query.hasOwnProperty('isEdit') ? _self.$route.query.isEdit : false;
      this.formDis = Boolean(this.$route.query.isLook)
      this.tinymceDis = Boolean(this.$route.query.isLook)
      const a = this.$route.query
      if (a.hasOwnProperty('isLook')) {
        // this.dataToHtml(a)
        // this.selectShow = true
        delete a.isLook;
      }
      if (a.hasOwnProperty('isEdit')) {
        // this.dataToHtml(a)
        // this.getTeacherList()
        // alert('编辑')
        this.getQuestionInfoFn(this.$route.query.id)
        this.eachQuestion()
        delete a.isEdit;
      }
    //   this.$store.dispatch('AddlistenForm', this.$route.query).then(() => {
    //   }).catch((err) => {
    //     Message.error(err.err)
    //   })
    } else { // 新增
      // this.getTeacherList()
    //   this.$store.dispatch('resetFunc').then(() => {
    //   }).catch((err) => {
    //     Message.error(err.err)
    //   })
    }
    // this.uploadData.token = GetQiniuToken().uploadToken
    this.ruleForm.courseId = this.$route.query.id
  },
  methods: {
    // 选择某一道题
    chooseScore(index) {
      this.courseNum = index + 1
      this.ruleForm = this.questionList[index]
      this.$refs['ruleForm'].clearValidate() // 去掉校验
      console.log(index)
    },
    getQuestionInfoFn(courseId) {
      console.log('courseId:::::::::', courseId)
      getQuestionInfo({ courseId }).then(res => {
        if (res.code === '200') {
          console.log(res)
          this.questionList = res.data
          this.ruleForm = res.data[0]
          this.eachQuestion()
        }
        console.log(res)
      })
    },
    // 添加大题
    nextQuestion(formName) {
      console.log(this.ruleForm)
      //   if (this.questionList.length >= this.limitQuestion) {
      //     Message.warning('最多上传100道题, 请点击提交按钮提交试题')
      //     return
      //   }
      if (this.questionList.length > 1) {
        this.ruleForm = this.questionList[this.questionList.length - 1]
        this.ruleForm.number = this.questionList.length
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.chooseCheck()) {
            Message.error('试题选项至少填两项')
            return
          }
          // this.questionList.push(this.ruleForm)
          this.ruleForm = {
            courseId: '',
            number: 0,
            title: '',
            score: '',
            optionsA: null,
            optionsB: null,
            optionsC: null,
            optionsD: null,
            answer: ''
          }
          this.courseNum = this.questionList.length + 1
          this.ruleForm.number = this.questionList.length + 1
          this.ruleForm.courseId = this.$route.query.id
          this.questionList.push(this.ruleForm)
          setTimeout(() => {
            this.$refs['ruleForm'].clearValidate() // 去掉校验
          })
        }
      })
    },
    // 删除当前大题
    delCur() {
      this.$confirm(`确定删除第${this.courseNum}道大题吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // this.questionList.pop()
        console.log(this.questionList[this.courseNum - 1])
        const haveId = this.questionList[this.courseNum - 1].id
        if (haveId) {
          console.log('有id需要调用接口')
          delsingleQuestion({ id: haveId }).then(res => {
            if (res.code === '200') {
              console.log('后端删除试题成功')
            } else {
              Message.error(res.message + '-', res.data)
            }
          })
        } else {
          console.log('没有id 不需要调用接口')
        }
        this.questionList.splice(this.courseNum - 1, 1)
        this.ruleForm = this.questionList[this.questionList.length - 1]
        this.eachQuestion()
        this.courseNum = this.questionList.length
        this.$refs['ruleForm'].clearValidate() // 去掉校验
      }).catch(() => {})
    },
    eachQuestion() {
      const arr = []
      for (let i = 0; i < this.questionList.length; i++) {
        this.questionList[i].number = i + 1
        arr.push(this.questionList[i])
      }
      return arr
    },

    chooseCheck() {
      const arr = []
      if (this.ruleForm.optionsA) arr.push(this.ruleForm.optionsA)
      if (this.ruleForm.optionsB) arr.push(this.ruleForm.optionsB)
      if (this.ruleForm.optionsC) arr.push(this.ruleForm.optionsC)
      if (this.ruleForm.optionsD) arr.push(this.ruleForm.optionsD)
      if (arr.length < 2) {
        Message.error('试题选项至少填两项')
        return false
      } else {
        return true
      }
    },
    request(data) {
      console.log(this.isEdit)
      this.isEdit ? editQuestion(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('编辑成功')
          this.$router.go(-1);
        } else {
          Message.error(response.message + '-' + response.data)
        }
      }) : addQuestion(data).then(response => {
        if (Number(response.code) === 200) {
          Message.success('新增成功')
          this.$router.go(-1);
        } else {
          Message.error(response.message + '-' + response.data)
        }
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.chooseCheck()) {
            Message.error('试题选项至少填两项')
            return
          }
          const newData = {
            courseQuestions: this.questionList
          }
          this.request(newData)
        } else {
          this.validateError()
          return false;
        }
      });
    }
  }
}
</script>

<style>
    .mt10{margin-top:10px;}
    .table{
        width: 100%;
        border-collapse: collapse;
        border-spacing: 0;
        margin-top: 20px;
        line-height: 30px;
    }

    .table thead{
        line-height: 30px;
        text-align: center;
        background: #f9f9f9;
        font-weight: bold;
        color: #333;
    }
    .table tbody{
        color: #666;
    }
    .table tbody td:nth-of-type(1){
        text-align: center;
    }
    .lineHeight{
        line-height: 40px;
    }
    .table td{
        border: 1px solid #ddd;
        padding: 5px 10px;
    }

  .tip {
    color: red;
  }
  .tin_box {
    border: 1px solid #ddd;
    padding: 0 10px 0 10px;
    color:#666;
  }
  .line{
    text-align: center;
  }
  .score_number{
    width: 96%;
    overflow: hidden;
  }
  .score_number li{
      width: 3%;
      height: 40px;
      line-height: 40px;
      margin: 0 1% 1% 0;
      border:1px solid #ddd;
      float: left;
      text-align: center;
      box-sizing: border-box;
      transition: all .2s;
      color:#666;
      cursor: pointer;
  }

  .score_number li:hover{
      background: cornflowerblue;
      color: #fff;
  }

  .score_number .active{
      background: cornflowerblue;
      color: #fff;
  }

  .score_number li span:nth-of-type(1){
      font-weight: bold;
  }
  .score_number li span:nth-of-type(2){
    display: inline-block;
    width:80%;
    font-size: 14px;
    overflow: hidden;
    text-overflow:ellipsis;
    white-space: nowrap;
  }

  .title{
      margin-left: 20px;
  }

  .isBlue{
      color: blue;
  }
  .isRed{
      color: red;
  }
  .isWhite{
      color: white;
  }
</style>
